import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity,
  Alert,
  Animated,
  Easing,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import { Camera, CameraView } from "expo-camera";
import React, { useEffect, useState, useRef } from "react";
import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router"; // 引入 useRouter
import { ToastAPI } from "@/components/Toast";
import { useTranslation } from "react-i18next";

export default function Authentication() {
  const { t } = useTranslation();

  const router = useRouter(); // 获取路由对象
  const [isCertifying, setIsCertifying] = useState(false);
  const cameraRef = useRef<any>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const animation = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (isCertifying) {
      Animated.loop(
        Animated.timing(animation, {
          toValue: 1,
          duration: 2000, // 动画总时长，这里设置为 4000ms 以匹配来回扫动
          easing: Easing.linear,
          useNativeDriver: true,
        })
      ).start();
    } else {
      animation.stopAnimation();
      animation.setValue(0);
    }
  }, [isCertifying]);

  const translateY = animation.interpolate({
    inputRange: [0, 0.5, 1],
    outputRange: [-250, 250, -250],
  });

  const handleCertify = async () => {
    const { status } = await Camera.requestCameraPermissionsAsync();
    if (status === "granted") {
      setIsCertifying(true);
      timerRef.current = setTimeout(() => {
        ToastAPI.success(t("recognition.authentication_success"));
        router.back();
      }, 5000);
    } else {
      ToastAPI.warning(t("recognition.grant_camera_permission"));
    }
  };

  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={() => router.back()}>
            <Image
              source={require("@/assets/images/return-left.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center">
            <Text className="text-[#fff] text-[18px]">
              {t("recognition.video_authentication")}
            </Text>
          </View>
          <View className="w-[18px]"></View>
        </View>
        <View className="mt-[50px] flex-row justify-center items-center">
          <View>
            <Text className="text-[#fff] text-[18px]">
              {t("recognition.ensure_sound_camera")}
            </Text>
            <Text className="text-[#fff] text-[18px] text-center mt-[5px]">
              {t("recognition.no_headphones")}
            </Text>
          </View>
        </View>
        <View className="mt-[50px] flex-row justify-center items-center">
          {isCertifying ? (
            <View
              style={{
                width: 250,
                height: 250,
                borderRadius: 125,
                overflow: "hidden",
                borderWidth: 2,
                borderColor: "#fff",
                position: "relative",
              }}
            >
              <CameraView
                ref={cameraRef}
                style={{ width: 250, height: 250 }}
                facing="front"
              />
              <Animated.View
                style={[
                  {
                    position: "absolute",
                    top: 0,
                    left: 0,
                    right: 0,
                    height: 10,
                    backgroundColor: "rgba(60, 134, 255, 0.5)",
                    transform: [{ translateY }],
                  },
                ]}
              />
            </View>
          ) : (
            <Image
              source={require("@/assets/images/lian.png")}
              className="w-[250px] h-[250px]"
            />
          )}
        </View>

        {!isCertifying && (
          <View style={styles.footer}>
            <TouchableOpacity onPress={handleCertify}>
              <LinearGradient
                style={styles.loginBtn}
                colors={["#3D7FFF", "#6FC2FA"]}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 0 }}
              >
                <Text className="text-[#fff] text-[16px]">
                  {t("recognition.authenticate")}
                </Text>
              </LinearGradient>
            </TouchableOpacity>
          </View>
        )}
      </View>
    </PageContainer>
  );
}

const styles = StyleSheet.create({
  footer: {
    position: "absolute",
    bottom: 13,
    left: 13,
    right: 13,
  },
  loginBtn: {
    height: 50,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 100,
  },
});
